import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const Login = () => import('../views/Login.vue')
const SideLayout = () => import('../components/SideLayout.vue')
const Dashboard = () => import('../views/Dashboard.vue')
const Issues = () => import('../views/Issues.vue')
const IssueDetail = () => import('../views/IssueDetail.vue')
const Knowledge = () => import('../views/Knowledge.vue')
const Reviews = () => import('../views/Reviews.vue')
const Profile = () => import('../views/Profile.vue')
const Exams = () => import('../views/Exams.vue')

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/login', name: 'login', component: Login },
    {
      path: '/',
      component: SideLayout,
      meta: { requiresAuth: true },
      children: [
        { path: '', name: 'dashboard', component: Dashboard },
        { path: 'issues', name: 'issues', component: Issues },
        { path: 'issues/:id', name: 'issue-detail', component: IssueDetail },
        { path: 'knowledge', name: 'knowledge', component: Knowledge },
        { path: 'reviews', name: 'reviews', component: Reviews },
        { path: 'profile', name: 'profile', component: Profile },
        { path: 'exams', name: 'exams', component: Exams },
      ]
    },
  ]
})

router.beforeEach((to) => {
  const auth = useAuthStore()
  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
})

export default router
